package com.neusoft.db;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.neusoft.myutils.MyUtils;

public class DBDriver {
	/**
	 * 获取数据库的连接对象 返回数据库的连接对象
	 * 
	 */
	public Connection getConn() {
		Connection conn = null;
		try {
			InputStream is = this.getClass().getClassLoader().getResourceAsStream("db.properties");
			Properties prop = new Properties();
			prop.load(is);
			String URL = prop.getProperty("URL");
			String userName = prop.getProperty("userName");
			String password = prop.getProperty("password");
			conn = DriverManager.getConnection(URL, userName, password);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("获取数据库连接异常：" + e.getMessage());
			e.printStackTrace();
		}
		return conn;
	}

	public List<Map<String, Object>> doQueryListMap(String strSql) {
		ResultSet rs = doQuery(strSql);
		List<Map<String, Object>> lsts = MyUtils.converResultSet2List(rs);
		this.close(rs);
		return lsts;
	}

	/**
	 * 数据库查询操作
	 * 
	 * @param strSql
	 *            查询sql语句
	 * @return 返回结果集resultset
	 */
	public ResultSet doQuery(String strSql) {
		ResultSet rs = null;
		try {
			Statement st = getConn().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
			rs = st.executeQuery(strSql);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return rs;
	}

	/**
	 * 数据库的操作（可以执行update/delete/insert/ddl语句）
	 * 
	 * @param strSql
	 * @return
	 */
	public int doUpdate(String strSql) {
		int re_i = 0;
		try {
			Statement st = getConn().createStatement();
			re_i = st.executeUpdate(strSql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return re_i;
	}

	/**
	 * 关闭数据连接
	 * 
	 * @param conn
	 */
	public void close(Connection conn) {
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void close(ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}
	}
}
